var mslibrary = require('ms-common-library');

module.exports = function (UC, source, config, ArFor, cache) {
    var UserControl = UC;
    var PrintServer = function (ps, req, Order_id, admin_off) {

        var user_url = config.getdomain(req, '/Products/Order/printer/user/' + Order_id + '/');

        var admin_url = config.getdomain(req, '/Products/Order/printer/admin/' + Order_id + '/');

        var admin = function () {
            if (admin_off) {
                user()
                return
            }
            new source("1e0qcsvs6", {
                Order_id: Order_id
            }, function (Rows, error) {
                if (error) {
                    Rows = []
                } else {
                    Rows = Rows.Table;
                }
                new mslibrary.ArFor(Rows, function () {
                    user()
                }).forEach(function (obj, next) {
                    if (obj.printer_id == 2) {
                        next()
                    } else {
                        var url = admin_url.replace('/' + Order_id + '/', '/' + Order_id + '_' + obj.printer_id + '/');
                        ps.add(url, function (db) {
                            if (db && db.error == 0) {
                                new source('1e0qcsvs3', {
                                    Order_id: Order_id,
                                    printer_id: obj.printer_id
                                }, function (db) {
                                    next()
                                })
                            } else {
                                next()
                            }
                        })
                    }
                })
            })
        }
        var user = function () {
            ps.add(user_url, function (error) {
                // console.log(error)
            })
        }
        admin();
    }
    var addOrder = function (obj, Callback) {

        obj._dateTime = (new Date()).getTime();

        var SQLObj = {
            SQL: "INSERT INTO OrderForm([payment],[_dateTime],[cateringPosition_id],[user_id],[Order_id],[Order_status],[Creation_Date]) values ({payment},{_dateTime},{cateringPosition_id},{user_id},'{Order_id}',1,datetime('now','+8 hour'))",
            type: "add"
        };

        new source(SQLObj, obj, function (db) {
            Callback(db);
        });

    }
    var router = function (req, res, next) {

        var ps = config.Products_Print_Server;
        if (UserControl.getoff(req.session.key)) {

            var Request = req.body;

            var U = UserControl.GetForm(req.session.key, {});

            var Orders_id = U.user_id + '' + new Date().getTime();


            if (Request.type == "Orders") {

                var obj = UserControl.GetForm(req.session.key, {
                    Order_id: Orders_id,
                    cateringPosition_id: Request.cateringPosition_id,
                    payment: Request.payment
                });
                addOrder(obj, function (OrderForm) {
                    if (OrderForm && OrderForm.id) {


                        var List = Request.jsondb;

                        List = JSON.parse(List);

                        new ArFor(List, function () {
                            PrintServer(ps, req, Orders_id)
                            res.Json({
                                "error": 0,
                                Order: Orders_id
                            });
                        }).forEach(function (item, _next) {
                            item.Order_id = Orders_id;
                            item.OrderForm_id = OrderForm.id
                            item._dateTime = (new Date()).getTime();
                            item = UserControl.GetForm(req.session.key, item);
                            var SQLObj = {
                                SQL: "INSERT INTO OrderDetails(OrderForm_id,_dateTime,Products_id,Price,amount,user_id,Order_id,Order_status,Creation_Date) SELECT {OrderForm_id} as OrderForm_id,{_dateTime} as _dateTime, ps.id as Products_id, ps.Price, {len} as amount,{user_id} as user_id, '{Order_id}' as Order_id, (IFNULL(pt.Printer_id==2,1)+2) as Order_status, datetime('now','+8 hour') AS Creation_Date FROM Products AS ps INNER JOIN ProductsType AS pt ON ps.type = pt.id where ps.id={id};",
                                type: "add"
                            };
                            new source(SQLObj, item, function (OrderDetails) {
                                _next();
                            });
                        });
                    } else {
                        res.Json({
                            "error": 1003
                        });
                    }
                })
            } else {
                res.Json({
                    "error": 1002
                });
            };

            Request = UserControl.GetForm(req.session.key, Request);

        } else {

            res.Json({
                "error": 1001
            });

        };

    };

    return router;
};